//
//  UIImageView+Cache.m
//  MKWebImage
//
//  Created by lily on 17/1/2.
//  Copyright © 2017年 lily. All rights reserved.
//

#import "UIImageView+Cache.h"
#import <objc/runtime.h>

static char *ImageLoaderKey;
@implementation UIImageView (Cache)

- (void)mk_setImageWithUrl:(NSString *)url placeHolder:(UIImage *)holder complete:(void(^)(UIImage *image, BOOL cache))complete {
    [self mk_setImageWithUrl:url placeHolder:holder options:MKLoadDefaultOption complete:complete];
}

- (void)mk_setImageWithUrl:(NSString *)url placeHolder:(UIImage *)holder options:(MKLoadOptions)options complete:(void(^)(UIImage *image, BOOL cache))complete {
    
    //cancel相关联的loader
    [self cancelImageLoadWithKey:@"currentLoadImage" removeFromQueue:YES];
    
    if (holder) {
        self.image = holder;
    }
    __weak typeof(self) weakself = self;
    MKImageDownloader *loader = [[MKImageManager shareInstance] downloadWithUrl:url option:options complete:^(UIImage *image, BOOL cache, NSError *error) {
        
        [weakself cancelImageLoadWithKey:@"currentLoadImage" removeFromQueue:NO];
        
        if (image) {
            weakself.image = image;
        }
        if (complete) {
            complete(image, cache);
        }
    }];
    
    //将loader关联到imageview上
    if (loader) {
        [[self loadImage] setObject:loader forKey:@"currentLoadImage"];
    }
}

- (void)cancelImageLoadWithKey:(NSString *)key removeFromQueue:(BOOL)remove {
    MKImageDownloader *loader = [[self loadImage] objectForKey:key];
    if (loader) {
        if (remove) {
            [[MKImageManager shareInstance] removeLoader:loader];
        }
        [((NSMutableDictionary *)[self loadImage]) removeObjectForKey:key];
    }
}

- (NSMutableDictionary *)loadImage {
    NSMutableDictionary *loadDict = objc_getAssociatedObject(self, &ImageLoaderKey);
    if (!loadDict) {
        loadDict = [NSMutableDictionary dictionary];
        objc_setAssociatedObject(self, &ImageLoaderKey, loadDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    }
    return loadDict;
}
@end
